package com.xiaoquan.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiaoquan.common.constant.ProductConstant;
import com.xiaoquan.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.xiaoquan.gulimall.product.dao.AttrGroupDao;
import com.xiaoquan.gulimall.product.dao.CategoryDao;
import com.xiaoquan.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.xiaoquan.gulimall.product.entity.AttrGroupEntity;
import com.xiaoquan.gulimall.product.entity.CategoryEntity;
import com.xiaoquan.gulimall.product.service.CategoryService;
import com.xiaoquan.gulimall.product.vo.AttrGroupRelationVo;
import com.xiaoquan.gulimall.product.vo.AttrRespVo;
import com.xiaoquan.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoquan.common.utils.PageUtils;
import com.xiaoquan.common.utils.Query;

import com.xiaoquan.gulimall.product.dao.AttrDao;
import com.xiaoquan.gulimall.product.entity.AttrEntity;
import com.xiaoquan.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrDao attrDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    // TODO 将页面的属性值 VO  赋值给数据库中的属性 DAO
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        // 使用工具类 进行复制  就是将attr 赋值给 attrEntity; 将旧数据赋值给新数据 前面时旧的 后面是新的
        BeanUtils.copyProperties(attr, attrEntity);
        // 1、保存基本数据
        this.updateById(attrEntity);
        // 2、保存关联关系
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()
                && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }


    // 分页 和获取类目规格参数
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type","base".equalsIgnoreCase(type) // 以后数据库改了 就不用改代码了 直接改常量值
                        ?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()
                        :ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode()); // 每次查询都要判断
        if (catelogId != 0  ) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");  // key是检索条件 就是用户在收索框输入的值
        if (!StringUtils.isEmpty(key)) {
            // 搜索功能 attr_id attr_name
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        //  records：记录
        List<AttrEntity> records = page.getRecords();

        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            // 设置分类和分组的名字
            // 1、设置分组的名字
            if ("base".equalsIgnoreCase(type)) { // 销售属性是不存在分组的
                AttrAttrgroupRelationEntity attrId = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrEntity.getAttrId()));
                if (attrId != null && attrId.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrId.getAttrGroupId());
                    attrRespVo.setCatelogName(attrGroupEntity.getAttrGroupName());
                }
            }
            // 2、设置分类的名称
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());  // 变成一个List集合

        pageUtils.setList(respVos);  // 结果集用最新的
        return pageUtils;
    }

    // TODO BeanUtils 将一个对象的值 赋值给另一个对象
    @Cacheable(value = "attr",key = "'attrinfo:'+#root.args[0]") // 获取方法第0和参数名字
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        //  当 当前数据所显示的类型与查询的数据不一致时 构造 -->查询 全部复制给 显示数据类型
        AttrRespVo respVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,respVo);

        // 基本属性（规格参数）才有分组功能
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 1、 设置分组信息
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrId));
            if (relationEntity != null) {
                respVo.setAttrGroupId(relationEntity.getAttrId()); // respVo.setAttrGroupId();  设置属性分组id
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrId());
                if (attrGroupEntity != null) {
                    respVo.setAttrName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        // 2、设置分类信息
        Long catelogId = attrEntity.getCatelogId();  // 查询这个分类的完整路径

        // respVo.setCatelogPath();  设置完整路径名 调用递归方法
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        respVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity !=null) {
            respVo.setCatelogName(categoryEntity.getName());
        }

        return respVo;
    }

    // TODO  xxxDao.selectCount 是否大于0 进行判断操作
    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        //  0是销售属性 1是基本属性  销售属性不需要维护
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 1、修改分组关联
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
            Integer count = attrAttrgroupRelationDao.selectCount(new UpdateWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attr.getAttrId()));

            if (count > 0) { //  count大于0  说名 原本存在属性  就是修改操作
                attrAttrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attr.getAttrId()));
            } else { // 否则就是 新增操作
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }
    }

    /**
     * 根据分组id 查找关联的所有基本属性（规格参数）
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {

        //TODO 利用id 在 中间表中查询 多个对象
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrgroupId));
        List<Long> attrIds  = entities.stream().map((attr) -> { // 把对象中的attr_id 收集成数组
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if(attrIds == null || attrIds.size() == 0){
            return null;
        }

        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);

        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        //attrAttrgroupRelationDao.delete(new QueryWrapper<AttrAttrgroupRelationEntity>()
        //.eq("attr_id",1L).eq("attr_group_id",1L));  这个方法要执行删除很多次 不太好

        // TODO 自定义删除方法 只执行一次
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationDao.deleteBatchRelation(entities);
    }

    /**
     *  13、获取属性分组没有关联的其他属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        // 1、当前分组只能关联自己所属分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId); // attrgroupId 2
        Long catelogId = attrGroupEntity.getCatelogId();  // catelogId 225
        // 2、当前分组只能关联别的分组没有引用的属性
        // 2.1）、当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId)); // .ne("attr_group_id",attrgroupId)
        List<Long> collect = group.stream().map((item) -> { //  collect 2、7
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        // TODO 判空
        // 2.2）、这些分组关联的属性
        List<AttrAttrgroupRelationEntity> attrIds = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .in("attr_group_id", collect));  // attrIds  11、13、15

        // 2.3）、从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
         wrapper.eq("catelog_id",catelogId)
                .eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (attrIds != null && attrIds.size()>0){
            wrapper.notIn("attr_id",attrIds);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

    @Override
    public List<Long> selectSearchAttrsIds(List<Long> attrValueIds) {
        // select attr_id from `pms_attr` where attr_id IN(?) and search_type =1
        System.out.println("属性值id集合"+attrValueIds);
         return   this.baseMapper.selectSearchAttrsIds(attrValueIds);

    }

}